package com.jsgt.greekfire.ui.main

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.fhx.core.AppConfig
import com.fhx.core.base.BaseActivity
import com.fhx.core.goToActivity
import com.fhx.core.utils.*
import com.jsgt.greekfire.App
import com.jsgt.greekfire.IS_ACTIVATION
import com.jsgt.greekfire.LOGIN_STATUS
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.UpdateBean
import com.jsgt.greekfire.bean.UserBean
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.common.widget.TabButtonContainer
import com.jsgt.greekfire.event.MarketBuyOrSellEvent
import com.jsgt.greekfire.event.NetChangeEvent
import com.jsgt.greekfire.event.WalletInfoEvent
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.factory.WalletViewModelFactory
import com.jsgt.greekfire.ui.home.HomeFragment
import com.jsgt.greekfire.ui.home.entrance.EntranceActivity
import com.jsgt.greekfire.ui.main.adapter.DrawerMenuAdapter
import com.jsgt.greekfire.ui.main.adapter.model.DrawerMenu
import com.jsgt.greekfire.ui.main.invite.InviteActivity
import com.jsgt.greekfire.ui.main.updatedialog.UpdateDialogFragment
import com.jsgt.greekfire.ui.mainassets.MainAssetsFragment
import com.jsgt.greekfire.ui.market.MarketFragment
import com.jsgt.greekfire.ui.mine.sermoncommunity.SermonCommunityActivity
import com.jsgt.greekfire.ui.mine.user.address.AddressActivity
import com.jsgt.greekfire.ui.mine.user.backupwalletword.BackUpWalletWordActivity
import com.jsgt.greekfire.ui.mine.user.language.LanguageActivity
import com.jsgt.greekfire.ui.mine.user.messagelist.MessageListActivity
import com.jsgt.greekfire.ui.mine.user.securityset.SecuritySetActivity
import com.jsgt.greekfire.ui.news.NewsFragment
import com.jsgt.greekfire.ui.trading.TradingFragment
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.jsgt.greekfire.viewmodel.WalletViewModel1
import kotlinx.android.synthetic.main.activity_main_group.*
import kotlinx.android.synthetic.main.content_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.backgroundColorResource
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.textColorResource

@Deprecated("带侧滑栏")
class MainGroupActivity : BaseActivity(), View.OnClickListener {
    val list: ArrayList<Class<*>> = ArrayList()
    private val listTitle: ArrayList<String> = ArrayList()
    private var indexTrading: Int = 0
    private var indexAssets: Int = 0

    private var version: String? = null
    private var updateBean: UpdateBean? = null
    private var updateDialogFragment: UpdateDialogFragment? = null
    private var isFirstCheckVersion: Boolean = true

    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }

    private val walletViewModel1: WalletViewModel1 by lazy {
        ViewModelProvider(
            this,
            WalletViewModelFactory()
        ).get(WalletViewModel1::class.java)
    }

    private val menuAdapter: DrawerMenuAdapter by lazy {
        DrawerMenuAdapter(R.layout.item_drawer_menu)
    }

    override fun getLayoutId(): Int = R.layout.activity_main_group

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        main_tab_container.resetState()
        setLoginState(LOGIN_STATUS)
    }

    var pattern = longArrayOf(50, 100, 150)
    override fun main() {
        userViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
        userViewModel.versionUpdateLiveData.observe(this, Observer {
//            showProgress(false)
//            if (updateDialogFragment == null) {
//                if (it?.Android != null && !TextUtils.isEmpty(it.Android!!.version)) {
//                    checkVersion = true
//                    if (AppConfig.getVersion()!! < it.Android!!.version!!) {
//                        val bundle = Bundle()
//                        bundle.putParcelable("bean", it)
//                        updateDialogFragment =
//                            UpdateDialogFragment()
//                        updateDialogFragment!!.arguments = bundle
//                        updateDialogFragment!!.show(supportFragmentManager, "updateFragment")
//                    }
//                }
//            }
            showProgress(false)
            App.context.setMemCache("appDownloadUrl", it.Android!!.url)
            version = it.Android!!.version.toString()
            updateBean = it
            showUploadDialog()
            isFirstCheckVersion = false
        })
        userViewModel.userInfoLiveData.observe(this, Observer {
            UserBean.instance.mobile = it.mobile
            UserBean.instance.email = it.email
        })

        //备份钱包的判断
        walletViewModel1.checkSecurityLiveData.observe(this, Observer {
            //showToast("密码验证成功")
            showProgress(false)
            pwdDialog?.dismiss()
            pwdDialog = null
            goToActivity<BackUpWalletWordActivity>()

        })
        walletViewModel1.errorLiveData.observe(this, Observer {
            showProgress(false)
        })

        list.add(HomeFragment::class.java) //首页
        listTitle.add(getString(R.string.home))
        list.add(MarketFragment::class.java) //行情
        listTitle.add(getString(R.string.market))
//        list.add(PoolFragment::class.java)
//        listTitle.add(getString(R.string.ore_pool))
        list.add(TradingFragment::class.java) //交易
        listTitle.add(getString(R.string.trading))
        indexTrading = list.size - 1
        // list.add(BaseCoinFragment::class.java)  //法币
        list.add(NewsFragment::class.java) //资讯
        listTitle.add(getString(R.string.news))
        //list.add(MineFragment::class.java) //资产
        list.add(MainAssetsFragment::class.java) //新的资产  白色背景
        listTitle.add(getString(R.string.assets))
        indexAssets = list.size - 1
        main_tab_container.setUp(R.id.fl_fragment_container, supportFragmentManager, list)
        setLoginState(LOGIN_STATUS)
        main_tab_container.resetState()
        main_tab_container.loginClick = { EntranceActivity.start(this) }
        main_tab_container.onTabSelectedListener =
            object : TabButtonContainer.OnTabSelectedListener {
                override fun onTabSelected(index: Int) {
                    // 当页面切换完成之后， 同时也要把 tab 设置到正确的位置
                    VibrateHelp.vComplicated(this@MainGroupActivity, pattern, -1)
                    refreshTitle(index)
                }
            }
        imv_title_left.setOnClickListener(this)

        //侧边栏相关
        imvPortrait.setOnClickListener(this)
        txvName.setOnClickListener(this)
        txvId.setOnClickListener(this)
        navigation_view.layoutParams.width = ScreenUtil.getScreenWidth(this) * 3 / 5
        recycler.layoutManager = LinearLayoutManager(this)
        recycler.adapter = menuAdapter
        menuAdapter.setNewInstance(getDrawerMenuList())
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            if (menuAdapter.getItem(position).checkLogin && !LOGIN_STATUS) {
                main_tab_container.loginClick?.invoke()
                return@setOnItemClickListener
            }
            menuAdapter.getItem(position).click.invoke()
        }
        if (!LOGIN_STATUS) {
            txvName.text = getString(R.string.not_logged_in)
            txvId.visibility = View.GONE
            txvState.visibility = View.GONE
        } else {
            userViewModel.userInfo()
        }

//        if (LOGIN_STATUS) {
//            userViewModel.userInfo()
//        }
    }

    /**
     * 切换tab是刷新title样式
     */
    fun refreshTitle(index: Int) {
        if (index != indexTrading) {
            rl_title.visibility = View.VISIBLE
            txv_title.text = listTitle[index]
            if (index == indexAssets) {
                rl_title.backgroundColorResource = R.color.bg_main_title_asset
                txv_title.textColorResource = R.color.text_main_title_asset
                imv_title_left.imageResource = R.mipmap.ic_main_title_account_white
                setStatusBar(R.color.bg_main_title_asset, false, R.color.white)
            } else {
                rl_title.backgroundColorResource = R.color.bg_main_title
                txv_title.textColorResource = R.color.text_main_title
                imv_title_left.imageResource = R.mipmap.ic_main_title_account
                setStatusBar(R.color.bg_main_title, true, R.color.black)
            }
        } else {
            setStatusBar(R.color.bg_main_title, true, R.color.black)
            rl_title.visibility = View.GONE
        }
    }

    override fun onResume() {
        super.onResume()
        if (isFirstCheckVersion) {
            userViewModel.getAppVersion()
        }
        if (LOGIN_STATUS) {
            NetDataManager.getWalletInfo()
        }
    }

    override fun needSetStatusBar(): Boolean {
        return true
    }

    private fun getDrawerMenuList(): MutableList<DrawerMenu> {
        val list = mutableListOf(
            DrawerMenu(
                R.mipmap.ic_drawer_menu_pool,
                getString(R.string.main_drawer_menu_pool),
                true
            ) {
                //我的团队
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(this, getString(R.string.account_no_activation))
                } else {
                    //                goToActivity<MinersPurseActivity>()
                    goToActivity<SermonCommunityActivity>()
                }
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_wallet,
                getString(R.string.main_drawer_menu_wallet),
                true
            ) {
                //钱包管理
                goToActivity<EntranceActivity>()
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_address,
                getString(R.string.main_drawer_menu_address),
                true
            ) {
                //地址簿
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(this, getString(R.string.account_no_activation))
                } else {
                    goToActivity<AddressActivity>()
                }
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_language,
                getString(R.string.main_drawer_menu_language),
                false
            ) {
                //显示语言
//                ToastUtils.show(this, getString(R.string.not_yet_open))
                goToActivity<LanguageActivity>()
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_private_key,
                getString(R.string.main_drawer_menu_private_key),
                true
            ) {
                //钱包私钥
                //                goToActivity<EntranceActivity>()
                showInputPwdDialog()
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_update,
                getString(R.string.main_drawer_menu_update),
                false
            ) {
                //检查更新
                showProgress(true)
                isFirstCheckVersion = false
                userViewModel.getAppVersion()
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_notice,
                getString(R.string.main_drawer_menu_notice),
                false
            ) {
                //通知中心
                goToActivity<MessageListActivity>()
            },
            DrawerMenu(
                R.mipmap.ic_drawer_menu_safe,
                getString(R.string.main_drawer_menu_safe),
                true
            ) {
                // 安全设置
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(this, getString(R.string.account_no_activation))
                } else {
                    goToActivity<SecuritySetActivity>()
                }
            },
            DrawerMenu(
                // 邀请下载
                R.mipmap.ic_drawer_menu_down,
                getString(R.string.main_drawer_menu_down),
                false
            ) {
                if (App.context.getMemCache("appDownloadUrl") != null) {
                    goToActivity<InviteActivity>()
                } else {
                    ToastUtils.show(this, getString(R.string.not_yet_open))
                }
            }
        )
        if (LOGIN_STATUS) {
            list.add(DrawerMenu(
                R.mipmap.ic_drawer_menu_exit,
                getString(R.string.main_drawer_menu_exit),
                true
            ) {
                //退出
//                App.context.logout()
                logoutDialog.show()
            })
        }
        return list
    }

    //退出登录弹窗
    private val logoutDialog: Dialog by lazy {
        val contentView = layoutInflater.inflate(R.layout.dialog_logout, null, false)
        contentView.findViewById<TextView>(R.id.txv_cancel).setOnClickListener {
            logoutDialog.dismiss()
        }

        contentView.findViewById<TextView>(R.id.txv_ok).setOnClickListener {
            App.context.logout()
        }
        DialogUtil.show(this, contentView)
    }

    /**
     * 输入密码弹窗
     */
    var pwdDialog:Dialog ?= null
    private fun showInputPwdDialog() {
        val contentView = layoutInflater.inflate(R.layout.dialog_input_wallet_pwd, null, false)
        pwdDialog = DialogUtil.show(this, contentView)
        pwdDialog?.setCanceledOnTouchOutside(true)
        pwdDialog?.setCancelable(true)
        pwdDialog?.show()
        pwdDialog?.setOnDismissListener {
            pwdDialog = null
        }
        contentView.findViewById<TextView>(R.id.check_pwd_tv_cancel).setOnClickListener {
            pwdDialog?.dismiss()
        }

        contentView.findViewById<TextView>(R.id.check_pwd_tv).setOnClickListener {
            val pwd = contentView.findViewById<EditText>(R.id.pwd_et).text.toString().trim()
            if (TextUtils.isEmpty(pwd)) {
                showToast(getString(R.string.input_pwd_error_null))
            } else {
                //服务端验证
                walletViewModel1.checkWalletSecurityPwd(pwd)
                pwdDialog?.dismiss()
                showProgress(true)
            }
        }
    }

    /**
     * 版本升级弹窗
     */
    private fun showUploadDialog() {
        if (AppConfig.getVersion()!! < version!!) {
            val bundle = Bundle()
            bundle.putParcelable("bean", updateBean)
            updateDialogFragment = UpdateDialogFragment()
            updateDialogFragment!!.arguments = bundle
            updateDialogFragment!!.show(supportFragmentManager, "updateFragment")
        } else if (!isFirstCheckVersion) {
            val contentView =
                layoutInflater.inflate(R.layout.dialog_check_view, null, false)
            val versionDialog = DialogUtil.show(this, contentView)
            versionDialog.setCanceledOnTouchOutside(true)
            versionDialog.setCancelable(true)
            versionDialog.show()

            val itemVersion = contentView.findViewById<TextView>(R.id.item_version)

            itemVersion.text = "v" + AppConfig.getVersion()

            contentView.findViewById<TextView>(R.id.pop_sure).setOnClickListener {
                versionDialog.dismiss()
                showProgress(false)
            }
        }
        isFirstCheckVersion = false
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.imv_title_left -> {
                drawer_layout.openDrawer(navigation_view)
            }
            R.id.txvId, R.id.txvName, R.id.imvPortrait -> {
                if (LOGIN_STATUS) {

                } else {
                    EntranceActivity.start(this)
                }
            }
        }
    }

    /**
     * 设置是否已创建/导入钱包
     */
    private fun setLoginState(isLogin: Boolean) {
        main_tab_container.setLoginState(isLogin)
    }

    private var mLastClickBackTime //上次点击back键的时间
            : Long = 0

    override fun onBackPressed() {
        val curTime = System.currentTimeMillis()
        if (curTime - mLastClickBackTime > 2000) {
            mLastClickBackTime = curTime
            ToastUtils.show(this, getString(R.string.try_again_exit))
            return
        }
        super.onBackPressed()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetChangeEvent(e: NetChangeEvent) {
        if (NetworkUtil.isNetworkAvailable()) {
            if (isFirstCheckVersion) {
                userViewModel.getAppVersion()
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMarketBuyOrSellEvent(e: MarketBuyOrSellEvent) {
        if (main_tab_container.mCurPosition != 2) {
            btn_trading.performClick()

            main_tab_container.postDelayed({
                EventBus.getDefault().post(e)
            }, 500)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWalletInfoEvent(e: WalletInfoEvent) {
        showProgress(false)
        val info = NetDataManager.walletInfo ?: return
        txvName.text = info.walletName
//        txvId.visibility = View.VISIBLE
//        txvId.text = "ID:"
        txvState.visibility = View.VISIBLE
        txvState.text = if (IS_ACTIVATION == 1) {
            getString(R.string.not_activation)
        } else {
            getString(R.string.activated)
        }
    }
}
